package uk.ac.manchester.tewpl.iceiface.client.explorer;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.MessageBox;

import uk.ac.manchester.tewpl.iceiface.client.explorer.nodes.Airport;
import uk.ac.manchester.tewpl.iceiface.client.explorer.nodes.Node;
import uk.ac.manchester.tewpl.iceiface.client.explorer.nodes.Terminal;
import uk.ac.manchester.tewpl.iceiface.client.explorer.types.Mutable;
import uk.ac.manchester.tewpl.iceiface.client.explorer.types.Uri;
import uk.ac.manchester.tewpl.iceiface.client.model.KBIndividualModel;

/*
 * Shared utilities class for methods common to UI classes
 */
public class Utils {
	
	// Retrieve variables
	private Collection<Airport> airports = Registry.get("airports");
	private Mutable<Airport> airportSelected = Registry.get("airportSelected");
	private LinkedList<Airport> journey = Registry.get("journey");
	private ArrayList<KBIndividualModel> timePeriods = Registry.get("timePeriods");
	
	/*
	 * Return airport object from loaded airports, given the URI
	 */
	public Airport getCachedAirport(Uri uri) {		
		for (Airport airport : airports) { // For each airport
			if (airport.equals(uri))
				return airport;
		}
		
		// Nothing found
		return null;
	}
	
	/*
	 * Return terminal object from loaded terminals, given the URI
	 */
	public Terminal getCachedTerminal(Uri uri) {
		for (Airport airport : airports) { // For each airport
			for (Terminal terminal : airport.getTerminals()) // for each terminal
				if (uri.equals(terminal))
						return terminal;
		}
		
		// Nothing found
		return null;
	}
	
	/*
	 * Return cached node, either Airport or Terminal
	 */
	public Node getCachedNode(Uri uri) {
		
		// Check for airports
		Airport airport = getCachedAirport(uri);
		if (airport != null)
			return airport;
		
		// Check for terminals
		Terminal terminal = getCachedTerminal(uri);
		if (terminal != null)
			return terminal;
		
		// Nothing found
		return null;
	}
	
	/*
	 * Checks if the given airport is a valid destination for the airport
	 * at the bottom of the selection tree
	 */
	public boolean checkValidFinalDestination(Airport airport) {
		// If a journey exists, and the given airport isn't in it
		if (journey.size() > 0 && !journey.contains(airport))
			// Return true if the given airport is a legal route
			// out of the last airport in the journey
			return journey.getLast().getDestinations().contains(airport);
		else
			return false;
	}
	
}
